<?php

namespace api\wxapp\model;

use think\Model;
use think\Validate;
use api\wxapp\model\ShopGoods;
use api\wxapp\model\Goods;
use api\wxapp\model\OrderList;
class GoodsActivity extends Model
{
    protected $table = 'sssc_app_goods_activity';

    public function leftgoods($query)
    {
        // 按照创建时间排序
        return $query->join('goods t2','t2.id = t1.goods_id');
    }
    public function leftshop($query)
    {
        // 按照创建时间排序
        return $query->join('app_shop t3','t3.id = t1.shop_id');
    }
    //返回字段
    public function returnfiled($query)
    {
        // 按照创建时间排序
        return $query->field('t1.*,t3.name as shopname');
    }
    //模型验证
    public function check($data)
    {
        $validate = new Validate([
            'stime'  => 'require',
            'etime' => 'require',
            'goods_id' => 'require',
            'goods_price' => 'require',
        ]);
        if(!$validate->check($data)){
            return $validate->getError();
        }
    }
    //查询在售商品
    public function getgoods($shop_id)
    {
        $query = ShopGoods::alias('t1');
        $query = self::leftgoods($query);
        $goods = $query->field('t2.id,t2.name')->where('t1.shop_id',$shop_id)->select();
        return $goods;
    }
    //查询 正在进行的显示抢购活动
    public function online($shop_id)
    {
        //正在进行的活动
        $where[] = ['stime','elt',date('Y-m-d H:i:s',time())];
        $where[] = ['etime','egt',date('Y-m-d H:i:s',time())];
        $where[] = ['shop_id','eq',$shop_id];
        //上架的商品
        // $where[] = ['t1.status','eq',2];
        // $query = ShopGoods::alias('t1');
        // $query = self::leftgoods($query);
        // $query = self::leftshopgoods($query);
        // $goods = $query->field('t2.id,t2.name,t2.img,t3.stime,t3.etime')
        //     ->where($where)
        //     ->select();
        $list = self::where($where)->select()
        ->each(function($item, $key) use($shop_id){
            $value = json_decode($item['value']);
            $item['list'] = array();
            $newarr = array();
            foreach($value as $k=>$v){
                $arr = array();
                $goods = Goods::get($k);
                $arr['goods_id'] = $k;
                $arr['goods_price'] = $v;
                $arr['old_price'] = ShopGoods::where(['shop_id'=>$shop_id,'goods_id'=>$k])->value('price');
                $arr['img'] = $goods['img'];
                $arr['name'] = $goods['name'];
                $arr['count'] = OrderList::where(['shop_id'=>$shop_id,'goods_id'=>$k,'is_activity'=>$item['id']])->SUM('num');
                $newarr[] = $arr;
            }
            $item['list'] = $newarr;
            return $item;
        });

        return $list;
    }
    public function leftshopgoods($query)
    {
        // 按照创建时间排序
        return $query->join('app_goods_activity t3','t3.goods_id = t2.id');
    }

}
